package com.treeHole.treeHoleServer.service.impl;

import com.treeHole.treeHoleServer.mapper.*;
import com.treeHole.treeHoleServer.pojo.Comment;
import com.treeHole.treeHoleServer.pojo.Post;
import com.treeHole.treeHoleServer.pojo.RequestDataDTO.PostDeletePostDTO;
import com.treeHole.treeHoleServer.pojo.ResultDataDTO.*;
import com.treeHole.treeHoleServer.service.PostService;
import com.treeHole.treeHoleServer.utils.RandomUsernameGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;


/**
 * 负责用户与帖子进行交互的业务类实现
 */
@Slf4j
@Service
public class PostServiceImpl implements PostService {
    @Autowired
    private LikeMapper likeMapper;

    @Autowired
    private CollectMapper collectMapper;

    @Autowired
    private PostMapper postMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private PictureMapper pictureMapper;

    private void setUserPersonalOperationAndPicListOnPost(Integer userId, List<ResultPostDTO> resultPostDTOList) {
        for(ResultPostDTO post : resultPostDTOList){
            List<Integer> likeRecord=likeMapper.getUserIsLikePost(post.getPostId(),userId);
            if(likeRecord.isEmpty()){
                post.setIsLike(Boolean.FALSE);
            }else post.setIsLike(Boolean.TRUE);

            List<Integer> collectRecord=collectMapper.getUserIsCollectPost(post.getPostId(),userId);
            if(collectRecord.isEmpty()){
                post.setIsFavorite(Boolean.FALSE);
            }else post.setIsFavorite(Boolean.TRUE);

            List<Integer> commentRecord=commentMapper.getUserIsCommentPost(post.getPostId(),userId);
            if(commentRecord.isEmpty()){
                post.setIsComment(Boolean.FALSE);
            }else post.setIsComment(Boolean.TRUE);

            List<ResultURLDTO> picList=pictureMapper.getPostPictureURL(post.getPostId());
            post.setPic(picList);
        }
    }

    @Override
    public List<ResultPostDTO> getNewestPost(Integer tag, Integer userId, Integer page) {
        List<ResultPostDTO> resultPostDTOList = postMapper.getNewestPost(page*20 ,tag);

        setUserPersonalOperationAndPicListOnPost(userId, resultPostDTOList);
        log.info("服务层找到了{}条最新的帖子", resultPostDTOList.size());
        return resultPostDTOList;
    }

    @Override
    public List<ResultPostDTO> getHottestPost(Integer userId) {
        List<ResultPostDTO> resultPostDTOList = postMapper.getHottestPost();

        setUserPersonalOperationAndPicListOnPost(userId, resultPostDTOList);
        log.info("服务层找到了{}条最热的帖子", resultPostDTOList.size());
        return resultPostDTOList;
    }

    @Override
    public int userLikePost(Integer userId, Integer postId){
        log.info("服务层收到用户点赞帖子请求");
        return likeMapper.insertLikeRecord(postId,userId, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    @Override
    public int userUnlikePost(Integer userId, Integer postId) {
        log.info("服务层收到用户取消点赞请求");
        return likeMapper.deleteLikeRecord(postId,userId);
    }

    @Override
    public int userCollectPost(Integer userId, Integer postId) {
        log.info("服务层收到用户收藏请求");
        return collectMapper.insertCollectRecord(postId,userId, LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }

    @Override
    public int userUnCollectPost(Integer userId, Integer postId) {
        log.info("服务层收到用户取消收藏请求");
        return collectMapper.deleteCollectRecord(postId,userId);
    }

    @Override
    public List<ResultPostDTO> getUserPersonalPost(Integer userId, Integer page) {
        List<ResultPostDTO> resultPostDTOList = postMapper.getUserPersonalPost(userId,page*20);
        setUserPersonalOperationAndPicListOnPost(userId, resultPostDTOList);
        log.info("服务层收到获取个人发布的帖子请求,找到了{}条帖子",resultPostDTOList.size());
        return resultPostDTOList;
    }

    @Override
    public List<ResultPostDTO> getUserFavoritePost(Integer userId, Integer page) {
        List<ResultPostDTO> resultPostDTOList =postMapper.getUserCollectPost(userId,page*20);
        setUserPersonalOperationAndPicListOnPost(userId, resultPostDTOList);
        log.info("服务层收到获取个人收藏的帖子请求,找到了{}条帖子",resultPostDTOList.size());
        return resultPostDTOList;
    }

    @Override
    public ResultPostDetailDTO getPostDetail(Integer postId, Integer userId) {
        List<ResultPostDetailDTO> resultPostDTOList=postMapper.getPostFromPostId(postId);
        ResultPostDetailDTO post=resultPostDTOList.get(0);
        log.info("服务层获取帖子详情找到了{}条post表中的记录", resultPostDTOList.size());
        List<Integer> likeRecord=likeMapper.getUserIsLikePost(post.getPostId(),userId);
        if(likeRecord.isEmpty()){
            post.setIsLike(Boolean.FALSE);
        }else post.setIsLike(Boolean.TRUE);

        List<Integer> collectRecord=collectMapper.getUserIsCollectPost(post.getPostId(),userId);
        if(collectRecord.isEmpty()){
            post.setIsFavorite(Boolean.FALSE);
        }else post.setIsFavorite(Boolean.TRUE);

        List<Integer> commentRecord=commentMapper.getUserIsCommentPost(post.getPostId(),userId);
        if(commentRecord.isEmpty()){
            post.setIsComment(Boolean.FALSE);
        }else post.setIsComment(Boolean.TRUE);

        List<ResultURLDTO> picList=pictureMapper.getPostPictureURL(post.getPostId());
        post.setPic(picList);

        String viewerName="";//浏览者昵称

        //构建评论列表
        List<Comment> originCommentList=commentMapper.getPostComment(postId,0);
        List<ResultPostDetailCommentDTO>  reCommentListTemp=new ArrayList<>();
        // 创建 SimpleDateFormat 对象，指定日期时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for(Comment c:originCommentList){
            if(Objects.equals(c.getUserId(), userId))viewerName=c.getUserName();
            if(c.getCommentType()==0){//对于帖子的评论
                ResultPostDetailCommentDTO mainCommentDTO=new ResultPostDetailCommentDTO();
                mainCommentDTO.setCmtId(c.getCommentId());
                mainCommentDTO.setCmtName(c.getUserName());
                mainCommentDTO.setPostId(c.getPostId());

                //将数据库中的时间字符串类型转化为时间戳
                try {
                    long timestamp=sdf.parse(c.getCommentDate()).getTime();
                    mainCommentDTO.setCmtTime(timestamp);
                }catch (ParseException e){
                    log.error(e.getMessage());
                }

                mainCommentDTO.setCmtContent(c.getContent());

                //在commentLike表中查询用户id与该评论id的数据,如果为空说明用户未点赞该评论
                List<Integer> cmtLikeRecordList=commentMapper.getUserIsLikeComment(userId,c.getCommentId());
                if(cmtLikeRecordList.isEmpty()){
                    mainCommentDTO.setIsLike(Boolean.FALSE);
                }else mainCommentDTO.setIsLike(Boolean.TRUE);

                //查找当前评论的点赞数
                mainCommentDTO.setCmtLikeCount(commentMapper.getCommentLikeCount(c.getCommentId()));
                mainCommentDTO.setType(c.getCommentType());
                mainCommentDTO.setCmtCmtId(c.getReCommentId());
                mainCommentDTO.setReplyUserName("");
                reCommentListTemp.add(mainCommentDTO);
            }
        }
        for(Comment c:originCommentList){
            if(c.getCommentType()==1){//对于评论的回复
                ResultCommentDTO subCommentDTO=new ResultCommentDTO();
                subCommentDTO.setCmtId(c.getCommentId());
                subCommentDTO.setCmtName(c.getUserName());
                subCommentDTO.setPostId(c.getPostId());

                //将数据库中的时间字符串类型转化为时间戳
                try {
                    long timestamp=sdf.parse(c.getCommentDate()).getTime();
                    subCommentDTO.setCmtTime(timestamp);
                }catch (ParseException e){
                    log.error(e.getMessage());
                }

                subCommentDTO.setCmtContent(c.getContent());

                //在commentLike表中查询用户id与该评论id的数据,如果为空说明用户未点赞该评论
                List<Integer> cmtLikeRecordList=commentMapper.getUserIsLikeComment(userId,c.getCommentId());
                if(cmtLikeRecordList.isEmpty()){
                    subCommentDTO.setIsLike(Boolean.FALSE);
                }else subCommentDTO.setIsLike(Boolean.TRUE);

                //查找当前评论的点赞数
                subCommentDTO.setCmtLikeCount(commentMapper.getCommentLikeCount(c.getCommentId()));

                //设置回复评论的特有字段
                subCommentDTO.setType(c.getCommentType());
                subCommentDTO.setCmtCmtId(c.getReCommentId());
                if(c.getReUserId()!=0){
                    subCommentDTO.setReplyUserName(commentMapper.getSpecificUserNameInPost(c.getReUserId(),postId));
                }else subCommentDTO.setReplyUserName("");

                //寻找合适的主评论,插入其回复列表,如果未找到主评论则直接丢弃
                for(ResultPostDetailCommentDTO mainc:reCommentListTemp){
                    if(mainc.getCmtId().equals(c.getReCommentId())){
                        mainc.getReplyList().add(subCommentDTO);
                    }
                }
            }

        }
        post.setCommentName(viewerName);
        post.setCmtList(reCommentListTemp);
        return post;
    }

    @Override
    public Integer userCreatePost(PostDeletePostDTO postDTO) {
        Post post=new Post();
        post.setUserId(postDTO.getUserId());
        post.setTitle(postDTO.getTitle());
        post.setContent(postDTO.getContent());
        post.setCreateDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        post.setUserName(RandomUsernameGenerator.getDifName(new HashSet<>()));
        post.setTag(postDTO.getTag());
        Integer postId=0;
        postMapper.userCreatePost(post);
        List<String> urlList=postDTO.getPics();
        for( String url:urlList){
            pictureMapper.userPostPostPicture(postDTO.getPostId(),url,
                    LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        }
        log.info("服务层新建了帖子,postId={}",post.getPostId());
        return postId;
    }

    @Override
    public int userDeletePost(Integer postId) {
        int resultCode=postMapper.userDeletePost(postId);
        pictureMapper.userDeletePostPicture(postId);
        return resultCode;
    }

    @Override
    public List<ResultPostDTO> searchPost(String keyword, Integer userId, Integer tag) {
        List<ResultPostDTO> resultPostDTOList;
        if(keyword.startsWith("#")){
            resultPostDTOList=postMapper.searchPostByPostId(Integer.parseInt(keyword.substring(1)));
            setUserPersonalOperationAndPicListOnPost(userId,resultPostDTOList);
        }else{
            resultPostDTOList=postMapper.searchPostByKeyword(keyword,tag);
            setUserPersonalOperationAndPicListOnPost(userId,resultPostDTOList);
        }

        log.info("服务层收到查询帖子请求,找到了{}条帖子",resultPostDTOList.size());
        return resultPostDTOList;
    }


}
